<template>
  <el-upload
    action="#"
    name="file"
    :file-list="fileList"
    list-type="picture"
    :on-remove="onRemove"
    :http-request="httpRequest"
  >
    <slot />
  </el-upload>
</template>
<script>
import { uploadImageApi } from '@/api/user'
export default {
  name: 'UploadImg',
  props: {
    // 接收图片链接回显url
    img: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  created() {
    // 图片链接回显
    if (this.img) {
      this.fileList = [{
        url: 'http://124.223.14.236:8060/' + this.img,
        realtiveUrl: this.img
      }]
    }
  },
  methods: {
    // 删除文件钩子
    onRemove(file, fileList) {
      // 删除图片，同步fileList数组
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    async httpRequest(data) {
      const file = data.file
      const fd = new FormData()
      fd.append('file', file)
      const { data: res } = await uploadImageApi(fd)
      this.fileList = [{
        url: 'http://124.223.14.236:8060/' + res.savePath, // 显示图片
        realtiveUrl: res.savePath // 提交时图片地址
      }]
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
